<template>
  <el-drawer v-model="drawerVisible" title="修改密码" :size="300">
    <div class="drawer-main">
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="rules" label-position="top" status-icon>
        <el-form-item label="原密码" prop="password">
          <el-input placeholder="输入原密码" v-model="pwdForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" style="margin-top: 40px">
          <el-input placeholder="输入新密码" v-model="pwdForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item prop="newPasswordCopy">
          <el-input placeholder="再次输入新密码" v-model="pwdForm.newPasswordCopy" type="password" show-password />
        </el-form-item>
      </el-form>
      <div class="drawer-button-group">
        <el-row style="margin-bottom: 10px">
          <el-button type="primary" class="drawer-button" @click="submitForm">保存</el-button>
        </el-row>
        <el-row>
          <el-button type="info" class="drawer-button" @click="hideDrawer">取消</el-button>
        </el-row>
      </div>
    </div>
  </el-drawer>
</template>
<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { updatePassword } from '@api/uc/user'
import { ElMessage } from 'element-plus'
import { get } from '@/utils/param'
import { encrypt } from '@/utils/aes'
const passwordRule = get('PASSWORD_RULE')
const props = defineProps({
  modelValue: Boolean
})
const drawerVisible = computed({
  get() {
    return props.modelValue
  },
  set(v) {
    if (!v) {
      hideDrawer()
    }
  }
})
// const drawerVisible = ref(props.modelValue)
const pwdFormRef = ref<FormInstance>()

const pwdForm = reactive({
  password: '',
  newPassword: '',
  newPasswordCopy: ''
})

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
    return
  }
  if (passwordRule) {
    const arr = passwordRule.split('(and)')
    const reg = new RegExp(arr[0])
    if (!reg.test(value)) {
      callback(new Error(arr.length > 1 ? arr[1] : '密码不符合规范'))
    }
  }
  callback()
}

const validatePassCopy = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== pwdForm.newPassword) {
    callback(new Error('两次密码输入不一致!'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  password: [{ required: true, message: '原密码不能为空', trigger: 'change' }],
  newPassword: [
    { validator: validatePass, trigger: 'change' },
    { required: true, max: 20, message: '密码最大字符20', trigger: 'blur' }
  ],
  newPasswordCopy: [{ validator: validatePassCopy, trigger: 'change' }]
})

const submitForm = async () => {
  if (!pwdFormRef.value) return
  await pwdFormRef.value.validate((valid, fields) => {
    if (valid) {
      save()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = () => {
  if (!pwdFormRef.value) return
  pwdFormRef.value.resetFields()
}
const emit = defineEmits(['update:modelValue'])

function hideDrawer() {
  resetForm()
  emit('update:modelValue', false)
}
async function save() {
  try {
    const form = {
      password: encrypt(pwdForm.password),
      newPassword: encrypt(pwdForm.newPassword)
    }
    await updatePassword(form)
    ElMessage({
      type: 'success',
      message: '保存成功！'
    })
    hideDrawer()
  } catch (e) {
    console.error('修改密码失败', e)
  }
}
</script>
<style scoped lang="scss">
.drawer-main {
  height: 100%;
  position: relative;

  .drawer-button-group {
    position: absolute;
    bottom: 0px;
    width: 100%;

    .drawer-button {
      width: 100%;
    }
  }
}
</style>
